<?php
namespace app\index\controller;

use think\App;
use think\facade\Db;
use think\facade\Lang;
use think\facade\View;

class Main
{
    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    public $lang;
    public $site;
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }
    // 初始化
    protected function initialize()
    {
        // 站点相关
        $host = $_SERVER['HTTP_HOST'] ?? '';
        $site = Db::name('site')->where('host', $host)->find();
        if(!$site){
            throw new \Exception('站点不存在');
        }
        if(is_object($site)){
            $site = $site->toArray();
        }
        $site['icon_img'] = getFile($site['icon_img']);
        View::assign('site', $site);
        $this->site = $site;
        // 多语言相关
        $language = Db::name('language')->select();
        if(is_object($language)){
            $language = $language->toArray();
        }
        View::assign('language', $language);
        $this->lang = Db::name('language')->where('label', cookie('think_var'))->value('id');
        if(input('get.lang', '')){
            cookie('think_var', input('get.lang'), 60*60*24*365);
        }elseif(!cookie('think_var')){
            cookie('think_var', 'zh-cn', 60*60*24*365);
        }
        View::assign('lang', cookie('think_var'));
        config('app.default_lang', cookie('think_var'));
        // 分类相关
        $category = Db::name('category')
            ->where('language_id', $this->lang)
            ->where('site_id', $this->site['id'])
            ->where('pid', 0)
            ->select();
        if(is_object($category)){
            $category = $category->toArray();
        }
        foreach($category as $k => $v){
            $category[$k]['child'] = Db::name('category')
                ->where('pid', $v['id'])
                ->select();
            if(is_object($category[$k]['child'])){
                $category[$k]['child'] = $category[$k]['child']->toArray();
            }
        }
        View::assign('lang_label', Db::name('language')->where('id', $this->lang)->value('label'));
        View::assign('category', $category);
    }
}
